/*
 * @description 与业务相关的工具函数
 */

/** 调起微信支付 */
export function payOrder(params: WechatMiniprogram.RequestPaymentOption): Promise<any> {
  return new Promise((resolve, reject) => {
    wx.requestPayment({
      signType: 'MD5',
      ...params,
      success(res: unknown) {
        resolve(res)
      },
      fail(err: any) {
        reject(err)
      },
    })
  })
}

/** 获取微信登录的code,返回Promise */
export const getLoginCode = () => {
  return new Promise((resolve) => {
    wx.login({
      success(res) {
        resolve(res.code)
      },
      fail(err) {
        resolve('')
      },
    })
  })
}

/** 更新用户信息 */
export const updateUserInfo = async function () {
  const token = wx.$storage.getItemSync('token')
  if (!token) {
    return {
      Code: 0,
      Data: { CourseId: 0, Id: 0 },
      Msg: '未登录',
    }
  }
  const res = await wx.$http.post('/app/user/info')
  if (res.Code == 0) {
    wx.$storage.setItem('userInfo', res.Data)
  }
  return res
}

/** 弹出未登录的弹框 */
export function loginModal() {
  wx.$confirm({
    content: '您未登录，是否去登录',
  }).then(() => {
    wx.navigateTo({
      url: '/pages/login/index',
    })
  })
  wx.$storage.remove('token')
  wx.$storage.remove('userInfo')
}

/** 判断是否登录并且弹出模态框 */
export const isLoginModal = function () {
  const token = wx.$storage.getItemSync('token')
  if (!token) {
    loginModal()
    return false
  }
  return true
}
